package com.yoki.cloud.common.core.security;

import com.yoki.cloud.common.core.GlobalConst;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignTokenRequestInterceptor implements RequestInterceptor {

    private JwtConfigProperties jwtConfigProperties;

    public FeignTokenRequestInterceptor(JwtConfigProperties jwtConfigProperties) {
        this.jwtConfigProperties = jwtConfigProperties;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // token
        String tokenKey = jwtConfigProperties.getHeader();
        String token = request.getHeader(tokenKey);
        requestTemplate.header(tokenKey, token);

        // 多租户flag
        String tenantFlag = request.getHeader(GlobalConst.HEADER_TENANT_FLAG);
        requestTemplate.header(GlobalConst.HEADER_TENANT_FLAG, tenantFlag);
    }
}
